package com.example.transaction.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.transaction.sys.entity.Classfy;
import com.example.transaction.sys.entity.Item;
import com.example.transaction.sys.entity.Order;
import com.example.transaction.sys.service.IClassfyService;
import com.example.transaction.sys.service.IItemClassfyService;
import com.example.transaction.sys.service.IItemService;
import com.example.transaction.sys.service.IOrderService;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

@RestController
@RequestMapping("/sys/totalPrice")
public class TotalPriceController {

    private final IOrderService orderService;
    private final IItemService itemService;
    private final IItemClassfyService itemClassfyService;

    private final IClassfyService classfyService;

    public TotalPriceController(IOrderService orderService, IItemService itemService, IItemClassfyService itemClassfyService, IClassfyService classfyService) {
        this.orderService = orderService;
        this.itemService = itemService;
        this.itemClassfyService = itemClassfyService;
        this.classfyService = classfyService;
    }

//    /**
//     * 查询传入日期（及前五天）的种类名对应的总价格
//     * @param date
//     * @return
//     */
//    @GetMapping("/total")
//    public Map<LocalDate, List<Map<String, Object>>> getTotalPriceByDateAndStatus(@RequestParam("date") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
//        Map<LocalDate, List<Map<String, Object>>> totalPriceByDateAndClassify = new TreeMap<>();
//        for (int i = 0; i < 6; i++) {
//            LocalDate currentDate = date.minusDays(i);
//            String formattedDate = currentDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//            QueryWrapper<Order> orderWrapper = new QueryWrapper<>();
//            orderWrapper.eq("OrderStatus", "已完成")
//                    .apply("DATE_FORMAT(CreationTime, '%Y-%m-%d') = {0}", formattedDate);
//            List<Order> orders = orderService.list(orderWrapper);
//            List<Classfy> allClassifies = classfyService.list(); // 获取所有类别
//            Map<String, Double> totalPriceByClassify = new HashMap<>();
//            for (Order order : orders) {
//                Integer itemId = order.getItemID();
//                Item item = itemService.getById(itemId);
//                if (item != null) {
//                    Integer classfyID = itemClassfyService.getItemClassfyByItemId(itemId);
//                    String classifyName = classfyService.getById(classfyID).getClassfyName();
//                    if (classifyName != null) {
//                        Double price = item.getPrice();
//                        Double totalPrice = totalPriceByClassify.getOrDefault(classifyName, 0.0);
//                        totalPrice += price;
//                        totalPriceByClassify.put(classifyName, totalPrice);
//                    }
//                }
//            }
//            List<Map<String, Object>> totalPriceByClassifyList = new ArrayList<>();
//            for (Classfy classify : allClassifies) {
//                Map<String, Object> classifyData = new HashMap<>();
//                classifyData.put("date", currentDate);
//                classifyData.put("classfyName", classify.getClassfyName());
//                Double totalPrice = totalPriceByClassify.getOrDefault(classify.getClassfyName(), 0.0);
//                classifyData.put("totalPrice", totalPrice);
//                totalPriceByClassifyList.add(classifyData);
//            }
//            totalPriceByDateAndClassify.put(currentDate, totalPriceByClassifyList);
//        }
//        return totalPriceByDateAndClassify;
//    }

    /**
     * 查询传入日期（及前五天）的种类名对应的总价格
     * @param date
     * @return
     */
    @GetMapping("/total")
    public Map<LocalDate, List<Map<String, Object>>> getTotalPriceByDateAndStatus(@RequestParam("date") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
        Map<LocalDate, List<Map<String, Object>>> totalPriceByDateAndClassify = new TreeMap<>();
        for (int i = 0; i < 6; i++) {
            LocalDate currentDate = date.minusDays(i);
            String formattedDate = currentDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            QueryWrapper<Order> orderWrapper = new QueryWrapper<>();
            orderWrapper.eq("OrderStatus", "已完成")
                    .apply("DATE_FORMAT(CreationTime, '%Y-%m-%d') = {0}", formattedDate);
            List<Order> orders = orderService.list(orderWrapper);
            List<Classfy> allClassifies = classfyService.list(); // 获取所有类别
            Map<String, Double> totalPriceByClassify = new HashMap<>();
            for (Order order : orders) {
                Integer itemId = order.getItemID();
                Item item = itemService.getById(itemId);
                if (item != null) {
                    Integer classfyID = itemClassfyService.getItemClassfyByItemId(itemId);
                    if (classfyID != null) {
                        Classfy classfy = classfyService.getById(classfyID);
                        if (classfy != null) {
                            String classifyName = classfy.getClassfyName();
                            if (classifyName != null) {
                                Double price = item.getPrice();
                                Double totalPrice = totalPriceByClassify.getOrDefault(classifyName, 0.0);
                                totalPrice += price;
                                totalPriceByClassify.put(classifyName, totalPrice);
                            }
                        }
                    }
                }
            }
            List<Map<String, Object>> totalPriceByClassifyList = new ArrayList<>();
            for (Classfy classify : allClassifies) {
                Map<String, Object> classifyData = new HashMap<>();
                classifyData.put("date", currentDate);
                classifyData.put("classfyName", classify.getClassfyName());
                Double totalPrice = totalPriceByClassify.getOrDefault(classify.getClassfyName(), 0.0);
                classifyData.put("totalPrice", totalPrice);
                totalPriceByClassifyList.add(classifyData);
            }
            totalPriceByDateAndClassify.put(currentDate, totalPriceByClassifyList);
        }
        return totalPriceByDateAndClassify;
    }


    /**
     * 查询传入日期的当天当周当月的种类名对应的总成交额
     * @param date
     * @return
     */
    @GetMapping("/recent")
    public Map<String, Map<String, Double>> getRecentStatus(@RequestParam("date") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
        Map<String, Map<String, Double>> totalPriceByCategory = new HashMap<>();

        // 查询给定日期的总成交额
        Map<String, Double> totalPriceForDate = getTotalPriceByCategory(date);
        if (totalPriceForDate != null) {
            totalPriceByCategory.put("本日", totalPriceForDate);
        } else {
            totalPriceByCategory.put("本日", new HashMap<>()); // 避免 NullPointerException
        }

        // 查询当前周的总成交额
        LocalDate startOfWeek = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDate endOfWeek = date.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
        Map<String, Double> totalPriceForWeek = getTotalPriceByCategory(startOfWeek, endOfWeek);
        if (totalPriceForWeek != null) {
            totalPriceByCategory.put("本周", totalPriceForWeek);
        } else {
            totalPriceByCategory.put("本周", new HashMap<>()); // 避免 NullPointerException
        }

        // 查询当前月份的总成交额
        LocalDate startOfMonth = date.with(TemporalAdjusters.firstDayOfMonth());
        LocalDate endOfMonth = date.with(TemporalAdjusters.lastDayOfMonth());
        Map<String, Double> totalPriceForMonth = getTotalPriceByCategory(startOfMonth, endOfMonth);
        if (totalPriceForMonth != null) {
            totalPriceByCategory.put("本月", totalPriceForMonth);
        } else {
            totalPriceByCategory.put("本月", new HashMap<>()); // 避免 NullPointerException
        }

        return totalPriceByCategory;
    }

    private Map<String, Double> getTotalPriceByCategory(LocalDate startDate, LocalDate endDate) {
        Map<String, Double> totalPriceByCategory = new HashMap<>();

        // 检查日期是否为空
        if (startDate == null || endDate == null) {
            throw new IllegalArgumentException("日期范围不能为空");
        }

        // 根据日期范围查询订单列表
        QueryWrapper<Order> orderWrapper = new QueryWrapper<>();
        orderWrapper.eq("OrderStatus", "已完成")
                .between("CreationTime", startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
        List<Order> orders = orderService.list(orderWrapper);

        // 获取所有类别列表
        List<Classfy> classfies = classfyService.list();

        // 初始化总成交额为0
        for (Classfy classfy : classfies) {
            totalPriceByCategory.put(classfy.getClassfyName(), 0.0);
        }

        for (Order order : orders) {
            if (order != null) {
                Integer itemId = order.getItemID();
                Item item = itemService.getById(itemId);
                if (item != null) {
                    Integer classfyID = itemClassfyService.getItemClassfyByItemId(itemId);
                    Classfy classfy = classfyService.getById(classfyID);
                    if (classfy != null) {
                        String classifyName = classfy.getClassfyName();
                        if (classifyName != null) {
                            Double price = item.getPrice();
                            Double totalPrice = totalPriceByCategory.getOrDefault(classifyName, 0.0);
                            totalPrice += price;
                            totalPriceByCategory.put(classifyName, totalPrice);
                        }
                    }
                }
            }
        }

        return totalPriceByCategory;
    }

    private Map<String, Double> getTotalPriceByCategory(LocalDate date) {
        if (date == null) {
            throw new IllegalArgumentException("日期不能为空");
        }
        return getTotalPriceByCategory(date, date);
    }




    /**
     * 通过orderID查找price和image
     * @param orderId
     * @return
     */
    @GetMapping("/item")
    public Map<String, Object> getItemDetailsByOrderId(@RequestParam("orderID") Integer orderId) {
        Map<String, Object> itemDetails = new HashMap<>();

        // 根据订单ID查询订单
        Order order = orderService.getById(orderId);
        if (order != null) {
            Integer itemId = order.getItemID();
            Item item = itemService.getById(itemId);
            if (item != null) {
                Double price = item.getPrice();
                String imageName = item.getItemImage();

                itemDetails.put("price", price);
                itemDetails.put("imageName", imageName);
            }
        }

        return itemDetails;
    }
}
